package com.zjh.photoshopstudy.app.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.zjh.photoshopstudy.Model.AppUserEntity;
import com.zjh.photoshopstudy.Utils.SharePreferencesUtils;
import com.zjh.photoshopstudy.app.MainActivity;
import com.zjh.photoshopstudy.R;
import com.zjh.photoshopstudy.app.register.RegisterActivity;
import com.zjh.photoshopstudy.app.user.RetrievePwdActivity;

public class LoginActivity extends AppCompatActivity {
    private EditText mUsernameEdit;
    private EditText mPasswordEdit;
    private LoginPresent mPresent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        AppUserEntity appUserEntity = SharePreferencesUtils.getLoginUser(this);
        if (appUserEntity==null) {
            init();
        }else {
            onLoginSuccess();
        }
    }

    private void init() {
        mUsernameEdit = findViewById(R.id.username_edit);
        mPasswordEdit = findViewById(R.id.password_edit);
        mPresent = new LoginPresent(this);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                doLogin();
                break;
            case R.id.register_btn:
                toRegisterActivity();
                break;
            case R.id.register_btn2:
                onLoginSuccess();
                break;
            case R.id.retrieve_pwd:
                toRetrievePwd();
                break;
        }

    }

    private void toRetrievePwd() {
        Intent intent = new Intent(this, RetrievePwdActivity.class);
        startActivity(intent);
    }

    private void doLogin() {
        String username = mUsernameEdit.getText().toString().trim();
        String password = mPasswordEdit.getText().toString().trim();
        mPresent.login(username, password);
    }

    public void onLoginSuccess() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    public void onLoginFail(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void toRegisterActivity() {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

}
